<template>
  <div class="login">
    <el-form
      :model="loginInfo"
      label-width="100px"
      class="loginForm"
      ref="login"
      :rules="rules"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="loginInfo.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="loginInfo.password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="login">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
//调用登录接口
import { userLogin } from "../util/axios";
export default {
  data() {
    return {
      loginInfo: {
        username: "",
        password: "",
      },
      //规则验证
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 2, max: 8, message: "长度在 2 到 8 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 16,
            message: "长度在 6 到 16 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    //封装一个登录事件
    login() {
      console.log(this.loginInfo, "表单");
      //当前验证器的方法是elementui提供的
      this.$refs.login.validate((val) => {
        if (val) {
          //验证成功之后就要调取接口
          userLogin(this.loginInfo).then((res) => {
            if (res.code == 200) {
              this.$store.dispatch("changeUserAction", res.list);
              this.$message.success(res.msg);
              //成功之后跳转到首页
              this.$router.push("/home");
            } else {
              this.$message.error(res.msg);
            }
          });
        } else {
          this.$message.error("用户名密码验证失败");
        }
      });
    },
  },
};
</script>

<style lang="stylus" scoped>
@import '../stylus/index.styl';

.login {
  width: 100vw;
  height: 100vh;
  background: $firstColor;
}

.loginForm {
  position: absolute;
  width: 400px;
  height: 200px;
  margin-top 15%
  margin-left 35%
}
</style>
